package com.jjx.trainingapi.common;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * @author LoveHuahua
 * @date 2022年05月06日 0:36
 * @description believe in yourself
 */
@Data
@Slf4j
public class BasePageDataVo<R> {
    /**
     * 总条数
     */
    private Long total;

    /**
     * 总记录
     */
    private List<R> records;


    /**
     * 分页数据转换
     *
     * @param records     记录
     * @param total       总数
     * @param targetClass 目标类
     * @return
     */
    public static <R> BasePageDataVo<R> convert(List<?> records, Long total, Class<R> targetClass) {
        BasePageDataVo<R> tBasePageDataVo = new BasePageDataVo<>();
        ArrayList<R> ts = new ArrayList<>();
        for (Object record : records) {
            if (record == null) {
                continue;
            }
            R o = null;
            try {
                o = (R) targetClass.newInstance();
            } catch (InstantiationException e) {
                log.error("创建实例失败,请检查无参构造", e);
                throw new RuntimeException(e);
            } catch (IllegalAccessException e) {
                log.error("创建实例失败,请检查权限", e);
                throw new RuntimeException(e);
            }
            BeanUtils.copyProperties(record, o);
            ts.add(o);
        }
        tBasePageDataVo.records = ts;
        tBasePageDataVo.total = total;
        return tBasePageDataVo;
    }

    /**
     * 转换为分页数据
     *
     * @param <R>
     * @return
     */
    public static <R> BasePageDataVo<R> convert(Page page, Class<R> targetClass){
        return convert(page.getRecords(), page.getTotal(), targetClass);
    }

}
